<?php

namespace App\Models;

use App\Http\Controllers\PdfController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 线上大赛作品审批打分模型
 * Class ArticleModel
 * @package app\common\model
 */
class CompetiteActivityWorksAppointScore extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'competite_activity_works_appoint_score';

    /**
     * 列表
     * @param page int 当前页
     * @param limit int 分页大小
     * @param con_id int 大赛id
     */
    public function lists($con_id, $limit = 10)
    {
        //获取所有的打分人
        $res = $this->select('score_manage_id', 'create_time')
            ->where('con_id', $con_id)
            ->groupBy('score_manage_id')
            ->paginate($limit)
            ->toArray();

        foreach ($res['data'] as $key => $val) {
            $works_info = $this->getScoreWorksSimple($con_id, $val['score_manage_id']);
            $res['data'][$key]['works_name'] = join(';', array_column($works_info, 'title'));
            $res['data'][$key]['manage_name'] = Manage::getManageNameByManageId($val['score_manage_id']);
        }
        return $res;
    }

    /**
     * 根据打分人获取所有的作品id，或名字  简单列表
     * @param score_manage_id
     */
    public function getScoreWorksSimple($con_id, $score_manage_id)
    {
        $res =  $this->from($this->getTable() . ' as s')
            ->select('w.id', 'w.serial_number', 'w.title')
            ->join('competite_activity_works as w', 'w.id', '=', 's.works_id')
            ->where('s.con_id', $con_id)
            ->where('s.score_manage_id', $score_manage_id)
            ->where('status', 1)
            ->where('is_violate', 1)
            ->get()
            ->toArray();
        return $res;
    }

    /**
     * 根据打分人获取所有的作品id，或名字 分页列表
     * @param score_manage_id
     */
    public function getScoreWorks($con_id, $score_manage_id, $limit = 10)
    {
        $res =  $this->from($this->getTable() . ' as s')
            ->select('w.id', 'w.serial_number', 'w.title', 'w.cover', 'w.type', 'w.user_id', 'w.group_id', 't.type_name', 'w.create_time')
            ->join('competite_activity_works as w', 'w.id', '=', 's.works_id')
            ->join('competite_activity_works_type as t', 't.id', '=', 'w.type_id')
            ->where('s.con_id', $con_id)
            ->where('s.score_manage_id', $score_manage_id)
            ->where('status', 1)
            ->where('is_violate', 1)
            ->paginate($limit)
            ->toArray();
        $competiteActivityGroupModel = new CompetiteActivityGroup();
        $userInfoModel = new UserInfo();
        foreach ($res['data'] as $key => $val) {
            if ($val['type'] == 1) {
                $user_info = $userInfoModel->getWechatField($val['user_id'], ['head_img', 'nickname']);
                $res['data'][$key]['head_img'] = $user_info['head_img'];
                $res['data'][$key]['nickname'] = $user_info['nickname'];
            } else {
                $group_info = $competiteActivityGroupModel->getGroupNameByGroupId($val['group_id'], ['name', 'img']);
                $res['data'][$key]['head_img'] = $group_info['img'];
                $res['data'][$key]['group_name'] = $group_info['name'];
            }
        }

        return $res;
    }

    /**
     * 添加、修改打分作品
     * @param con_id int 大赛id
     * @param score_manage_id 打分人
     * @param works_ids int 选择的作品  只传最后的作品 多个逗号拼接
     */
    public function modify($con_id, $score_manage_id, $works_ids, $type = 'change')
    {
        $works_ids = empty($works_ids) ? [] : explode(',', $works_ids);
        $works_ids = array_filter(array_unique($works_ids));
        $competiteActivityWorksScoreModel = new CompetiteActivityWorksScore();
        $is_exists = $competiteActivityWorksScoreModel->whereIn('works_id', $works_ids)->whereNotNull('review_score')->first();
        if ($is_exists) {
            throw new Exception('选择的作品存在已打分的情况，不能进行操作');
        }
        if ($type == 'add') {
            $works_ids_ed = [];
        } else {
            $works_ids_ed = $this->where('score_manage_id', $score_manage_id)->where('con_id', $con_id)->groupBy('works_id')->pluck('works_id')->toArray();
        }
        $works_ids_del = array_diff($works_ids_ed, $works_ids); //对比返回在 $works_ids_ed 中但是不在 $works_ids 的数据删除
        $works_ids_add = array_diff($works_ids, $works_ids_ed); //对比返回在 $works_ids 中但是不在 $works_ids_ed 的数据添加
        if (!empty($works_ids_del)) {
            $this->whereIn('works_id', $works_ids_del)->where('score_manage_id', $score_manage_id)->where('con_id', $con_id)->delete();
            $this->resetScoreManageId($works_ids_del, $score_manage_id);
        }
        $data = [];
        foreach ($works_ids_add as $key => $val) {
            $data[$key]['con_id'] = $con_id;
            $data[$key]['score_manage_id'] = $score_manage_id;
            $data[$key]['works_id'] = $val;
            $data[$key]['create_time'] = date('Y-m-d H:i:s');

            //对应的打分人修改为指定
            $competiteActivityWorksScoreModel = new CompetiteActivityWorksScore();
            $competiteActivityWorksScoreModel->add([
                'works_id' => $val,
                'score_manage_id' => $score_manage_id,
                'type' => 2, //管理员手动分配
                'create_time' => date('Y-m-d H:i:s'),
            ]);

            //删除其余原本要打分的记录数据
            $competiteActivityWorksScoreModel->where('works_id', $val)->where('type', 1)->whereNull('review_score')->delete();
        }
        if (!empty($data)) $this->insert($data);
    }

    /**
     * 删除打分作品
     * @param con_id int 大赛id
     * @param score_manage_id 打分人
     * @param works_ids int 选择的作品  需要删除的作品，没有表示删除所有 多个逗号拼接
     */
    public function delScoreManage($con_id, $score_manage_id, $works_ids = null)
    {
        $works_ids = empty($works_ids) ? [] : explode(',', $works_ids);
        $works_ids = array_filter(array_unique($works_ids));

        $competiteActivityWorksScoreModel = new CompetiteActivityWorksScore();
        $is_exists = $competiteActivityWorksScoreModel->whereIn('works_id', $works_ids)->where('score_manage_id', $score_manage_id)->whereNotNull('review_score')->first();
        if ($is_exists) {
            throw new Exception('选择的作品存在已打分的情况，请勿删除');
        }
        $works_ids_ed = $this->where('score_manage_id', $score_manage_id)
            ->where('con_id', $con_id)
            ->where(function ($query) use ($works_ids) {
                if ($works_ids) {
                    $query->whereIn('works_id', $works_ids);
                }
            })
            ->groupBy('works_id')
            ->pluck('works_id')
            ->toArray();

        if (!empty($works_ids_ed)) {
            $this->whereIn('works_id', $works_ids_ed)->where('score_manage_id', $score_manage_id)->where('con_id', $con_id)->delete();
            $this->resetScoreManageId($works_ids_ed, $score_manage_id);
        }
    }
    /**
     * 判断当前作品是否包含自己打分，如果没有，则需要删除打分表的记录
     * @param works_ids
     */
    public function resetScoreManageId($works_ids, $score_manage_id)
    {
        $competiteActivityWorksScoreModel = new CompetiteActivityWorksScore();
        $competiteActivityWorksModel = new CompetiteActivityWorks();
        $competiteActivityWorksTypeModel = new CompetiteActivityWorksType();
        //判断当前作品是否包含自己打分，如果没有，则需要删除打分表的记录
        foreach ($works_ids as $key => $val) {
            $competiteActivityWorksScoreModel->where('works_id', $val)->where('score_manage_id', $score_manage_id)->where('type', 2)->whereNull('review_score')->delete();
            //判断删除后，还有没有其余打分的作品
            $is_exists = $competiteActivityWorksScoreModel->where('works_id', $val)->where('type', 2)->first();
            if (empty($is_exists)) {
                $works_type_id = $competiteActivityWorksModel->where('id', $val)->value('type_id');
                $works_type_score_manage_id = $competiteActivityWorksTypeModel->where('id', $works_type_id)->value('score_manage_id');
                $works_type_score_manage_id = explode(',' , $works_type_score_manage_id);
                foreach ($works_type_score_manage_id as $k => $v) {
                    $competiteAcivityWorksScoreModel = new CompetiteActivityWorksScore();
                    $competiteAcivityWorksScoreModel->add([
                        'works_id' => $val,
                        'review_score' => null,
                        'score_manage_id' => $v,
                        'type' => 1, //系统自动分配 
                    ]);
                }
            }
        }
    }
}
